package com.ruoyi.web.controller.business;

import com.ruoyi.common.core.controller.ApiBaseController;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.Bidi;
import java.util.Date;
import java.util.List;

/**
 * 商户订单管理
 */
@Api(description = "商户订单管理")
@Controller
@RequestMapping("/api/bus/order")
public class ApiBusOrderController extends ApiBaseController {

    @Autowired
    IShopUserService shopUserService;

    @Autowired
    IShopOrderService shopOrderService;

    @Autowired
    IBusinessShopService businessShopService;

    @Autowired
    IBusinessShopBalanceLogService businessShopBalanceLogService;

    @Autowired
    IBusinessShopInfoService businessShopInfoService;

    @Autowired
    IBusinessShopConfigService iBusinessShopConfigService;

    @Autowired
    IShopBalanceLogService shopBalanceLogService;

    //核销
    @GetMapping("/writeOff")
    @ResponseBody
    @Transactional
    public ApiResult writeOff(@RequestParam("password") String password,
                              @RequestParam("shopId") Long shopId,
                              @RequestParam("userName") String userName
                              )
    {
        BusinessShop businessShop = businessShopService.selectBusinessShopById(shopId);
        if (businessShop == null){
            return  ApiResult.error("商户不存在,请联系管理员");
        }

        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setCode(password);
        List<ShopOrder> shopOrderList = shopOrderService.selectShopOrderList(shopOrder);
        if (shopOrderList.size() == 0 ){
            return ApiResult.error("订单不存在,请扫描正确的二维码");
        }
        if (shopOrderList.size() > 1){
            return ApiResult.error("订单出现异常,请联系管理员");
        }

        ShopOrder actualShopOrder = shopOrderList.get(0);

        //判断状态
        Long status = actualShopOrder.getStatus();
        if (status != ShopOrder.Status.shipped.ordinal()){
            if (status == ShopOrder.Status.pendingPayment.ordinal()){
                return ApiResult.error("订单未支付,请先支付订单");
            }else{
                return ApiResult.error("订单状态非法,请核对是否订单已经核销");
            }
        }

        if (actualShopOrder.getBusinessShopId() != shopId){
            return  ApiResult.error("此订单是其他商户的");
        }

        actualShopOrder.setStatus(Long.valueOf(ShopOrder.Status.completed.ordinal()));
        actualShopOrder.setModifyDate(new Date());
        actualShopOrder.setUpdateBy(userName);

        BusinessShopBalanceLog businessShopBalanceLog = new BusinessShopBalanceLog();
        BusinessShopBalanceLog divideBusinessShopBalanceLog = new BusinessShopBalanceLog();

        //支付了多少钱就给多少钱
        businessShopBalanceLog.setChangAmount(actualShopOrder.getAmountPaid());
        businessShopBalanceLog.setType(1L);
        businessShopBalanceLog.setStatus(0L);
        businessShopBalanceLog.setOperator(businessShop.getName());
        businessShopBalanceLog.setCreateDate(new Date());
        businessShopBalanceLog.setApplyId(shopOrder.getId());

        BusinessShopInfo businessShopInfo = businessShopInfoService.selectBusinessShopInfoByShopId(shopId);
        if (businessShopInfo == null){
            //创建
            businessShopInfo = new BusinessShopInfo();
            businessShopInfo.setShopId(shopId);
            businessShopInfo.setBalance(0.00);
            businessShopInfo.setCreateTime(new Date());
            businessShopInfo.setUpdateTime(new Date());
            businessShopInfo.setPoints(0.00);
            businessShopInfo.setStatus(0L);
            businessShopInfoService.insertBusinessShopInfo(businessShopInfo);
        }
        BigDecimal changeAmount = BigDecimal.valueOf(actualShopOrder.getAmountPaid());

        //分成
        BusinessShopConfig businessShopConfig = iBusinessShopConfigService.selectBusinessShopConfigByShopId(businessShop.getId());
        if (businessShopConfig == null){
            return ApiResult.error("分成设置不存在,请联系管理员");
        }
        Long type = businessShopConfig.getType();
        ShopBalanceLog shopBalanceLog = null;
        Boolean isNeedDivide = false;
        if (type != BusinessShopConfig.type.year.getValue()){
            //不是年费模式 则开始收费
            isNeedDivide = true;
            if (type == BusinessShopConfig.divideType.regular.getValue()){
                //固定收费
                changeAmount = changeAmount.subtract(BigDecimal.valueOf(businessShopConfig.getValue())).setScale(2, BigDecimal.ROUND_HALF_UP );
                shopBalanceLog.setChangAmount(businessShopConfig.getValue());
                shopBalanceLog.setRelateId(actualShopOrder.getId());
                shopBalanceLog.setRelateObjectId(businessShop.getId());
                shopBalanceLog.setCreateDate(new Date());
                shopBalanceLog.setType(0L);
                shopBalanceLog.setStatus(0L);

                divideBusinessShopBalanceLog.setChangAmount(businessShopConfig.getValue());
                divideBusinessShopBalanceLog.setType(3L);  //固定被扣除
                divideBusinessShopBalanceLog.setStatus(0L);
                divideBusinessShopBalanceLog.setOperator(businessShop.getName());
                divideBusinessShopBalanceLog.setCreateDate(new Date());
                divideBusinessShopBalanceLog.setApplyId(shopOrder.getId());

            }
            else if (type == BusinessShopConfig.divideType.Percentage.getValue()){
                //百分比收费
                BigDecimal payAmount = BigDecimal.valueOf(actualShopOrder.getAmountPaid());
                BigDecimal value = payAmount.multiply(BigDecimal.valueOf(businessShopConfig.getValue())).setScale(2, BigDecimal.ROUND_HALF_UP);
                if (payAmount.compareTo(value) <= 0){
                    return ApiResult.error("分成比例出错");
                }
                changeAmount = changeAmount.subtract(value).setScale(2, BigDecimal.ROUND_HALF_UP );
                shopBalanceLog.setChangAmount(value.doubleValue());
                shopBalanceLog.setRelateId(actualShopOrder.getId());
                shopBalanceLog.setRelateObjectId(businessShop.getId());
                shopBalanceLog.setCreateDate(new Date());
                shopBalanceLog.setType(0L);
                shopBalanceLog.setStatus(0L);

                divideBusinessShopBalanceLog.setChangAmount(value.doubleValue());
                divideBusinessShopBalanceLog.setType(4L);  //百分比被扣除
                divideBusinessShopBalanceLog.setStatus(0L);
                divideBusinessShopBalanceLog.setOperator(businessShop.getName());
                divideBusinessShopBalanceLog.setCreateDate(new Date());
                divideBusinessShopBalanceLog.setApplyId(shopOrder.getId());
            }
        }

        //增加商户的余额
        BigDecimal balance = BigDecimal.valueOf(businessShopInfo.getBalance());
        balance = balance.add(changeAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
        businessShopInfo.setBalance(balance.doubleValue());

        businessShopInfoService.updateBusinessShopInfo(businessShopInfo);
        if (isNeedDivide){
            businessShopBalanceLogService.insertBusinessShopBalanceLog(divideBusinessShopBalanceLog);
            shopBalanceLogService.insertShopBalanceLog(shopBalanceLog);
        }
        businessShopBalanceLogService.insertBusinessShopBalanceLog(businessShopBalanceLog);
        shopOrderService.updateShopOrder(actualShopOrder);

        return ApiResult.success("订单核销成功");
    }

    @GetMapping("/details")
    @ResponseBody
    public ApiResult writeOff(@RequestParam("password") String password,
                              @RequestParam("shopId") Long shopId
    ) {
        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setCode(password);
        List<ShopOrder> shopOrderList = shopOrderService.selectShopOrderList(shopOrder);
        if (shopOrderList.size() == 0 ){
            return ApiResult.error("订单不存在");
        }
        if (shopOrderList.size() > 1){
            return ApiResult.error("此订单非法");
        }

        ShopOrder actualShopOrder = shopOrderList.get(0);

        if (actualShopOrder.getBusinessShopId() != shopId){
            return  ApiResult.error("此订单是其他商户的");
        }

        return ApiResult.success(actualShopOrder);
    }

}
